import _isUndefined from "lodash/isUndefined";
import _isNil from "lodash/isNil";
import React from 'react';
import { Badge, Dropdown, Icon, Menu, Tag, Tooltip } from 'antd';
import Big from 'big.js';
import moment from 'moment';
import { DEFAULT_DATE_FORMAT, DEFAULT_DATETIME_FORMAT, DEFAULT_TIME_FORMAT } from "./constants";
import intl from "./intl";
import { getDateFormat, getDateTimeFormat, getTimeFormat, getTimeZone } from "./utils";
var statusMap = ['error', 'success'];
var statusCodeMap = {
  S: 'success',
  F: 'error',
  P: 'default',
  RUNING: 'processing',
  PENDING: 'default',
  COMPLETE: 'success',
  ERROR: 'error',
  RUNNING: 'processing',
  NEW: 'default',
  PART: 'processing',
  SUCCESS: 'success',
  UNEXECUTE: 'default',
  FAILED: 'error'
};
/**
 Success
 Error
 Default
 Processing
 Warning
 */

/**
 * 返回 启用/禁用 对应的多语言 并加上状态
 * @param {0|1} v 启用状态
 * return 1 ? enable(多语言) : disabled(多语言)
 */

export function enableRender(v) {
  return /*#__PURE__*/React.createElement(Badge, {
    status: statusMap[v],
    text: v === 1 ? intl.get('cpaas.common.status.enable').d('启用') : intl.get('cpaas.common.status.disable').d('禁用')
  });
}
/**
 * 监控状态
 * @param {1|-1|any} flag
 * @return 1 -> 正常, -1 -> 故障, other -> 未在监控
 */

export function enableFlag(flag) {
  // eslint-disable-next-line no-nested-ternary
  return flag === 1 ? /*#__PURE__*/React.createElement("span", {
    style: {
      color: 'rgb(102, 205, 0)'
    }
  }, intl.get('cpaas.common.status.normal').d('正常')) : flag === -1 ? /*#__PURE__*/React.createElement("span", {
    style: {
      color: 'rgb(240, 65, 52)'
    }
  }, intl.get('cpaas.common.status.abnormal').d('故障')) : /*#__PURE__*/React.createElement("span", {
    style: {
      color: 'rgb(205, 133, 63)'
    }
  }, intl.get('cpaas.common.status.unmonitor').d('未在监控'));
}
/**
 * 返回 是/否 多语言 并加上对应的状态
 * @param {1|any} v 值
 * @return 1 -> yes(多语言), other -> no(多语言)
 */

export function yesOrNoRender(v) {
  return /*#__PURE__*/React.createElement(Badge, {
    status: statusMap[v],
    text: v === 1 ? intl.get('cpaas.common.status.yes').d('是') : intl.get('cpaas.common.status.no').d('否')
  });
}
/**
 * 渲染分页数据中的信息
 * @param {number} total - 数据总数
 * @param {number[]} range - [当前数据的第一条数据序号, 当前数据最后一条数据序号]
 */

export function totalRender(total, range) {
  return intl.get('cpaas.common.pagination.total', {
    range1: range[0],
    range2: range[1],
    total: total
  }).d("\u663E\u793A ".concat(range[0], " - ").concat(range[1], " \u5171 ").concat(total, " \u6761"));
}
/**
 * 返回 同步/异步 多语言
 * @param {1|any} v
 * @return 1 -> sync(多语言), other -> async(多语言)
 */

export function asyncRender(v) {
  return v === 1 ? intl.get('cpaas.common.status.sync').d('同步') : intl.get('cpaas.common.status.async').d('异步');
}
/**
 * 状态渲染
 * @param {string} v - 状态编码
 * @param {string} m - 状态描述
 * @returns ReactNode
 */

export function statusRender(v, m) {
  return /*#__PURE__*/React.createElement(Badge, {
    status: statusCodeMap[v],
    text: m || v
  });
}
/**
 * 优先级渲染(低中高)
 * @param {number} [v = 0] - 优先级数值
 * @returns ReactNode
 */

export function priorityRender() {
  var v = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
  // eslint-disable-next-line no-nested-ternary
  return v < 35 ? /*#__PURE__*/React.createElement("span", {
    style: {
      display: 'inline-block',
      width: '65%',
      background: '#52c41a'
    }
  }, intl.get('cpaas.common.priority.low').d('低')) : v > 65 ? /*#__PURE__*/React.createElement("span", {
    style: {
      display: 'inline-block',
      width: '65%',
      background: '#f5222d'
    }
  }, intl.get('cpaas.common.priority.high').d('高')) : /*#__PURE__*/React.createElement("span", {
    style: {
      display: 'inline-block',
      width: '65%',
      background: '#faad14'
    }
  }, intl.get('cpaas.common.priority.medium').d('中'));
}
/**
 * todo 到底需不需要这个.
 * 在dataList中返回code对应的meaning或name
 * 若不找不到，则返回code
 */

export function valueMapMeaning(dataList, code) {
  var target = dataList.find(function (item) {
    return item.value === code || item.code === code;
  });
  return _isUndefined(target) ? code : target.meaning || target.name;
}
/**
 * 流程状态
 */

export function processStatusRender(record) {
  // eslint-disable-next-line no-nested-ternary
  return record.endTime ? /*#__PURE__*/React.createElement(Tag, null, intl.get('cpaas.common.status.finished').d('已结束')) : record.suspended ? /*#__PURE__*/React.createElement(Tag, {
    color: "orange"
  }, intl.get('cpaas.common.status.suspended').d('挂起中')) : /*#__PURE__*/React.createElement(Tag, {
    color: "green"
  }, intl.get('cpaas.common.status.running').d('运行中'));
}
/**
 * 流程的已读未读状态
 * @param {'Y'|'N'} v
 * @return 'Y' || 1 -> read, 'N' || 0 -> unread, other -> ''
 */

export function readFlagRender(v) {
  // eslint-disable-next-line no-nested-ternary
  return v === 'Y' || v === 1 ? intl.get('cpaas.common.status.read').d('已读') : v === 'N' || v === 0 ? intl.get('cpaas.common.status.unread').d('未读') : '';
}
/**
 * 日期(date)的 render
 * @param {?String} dateStr - 日期的字符串
 */

export function dateRender(dateStr) {
  var dateTemplate = getDateFormat();
  return dateStr && moment(dateStr, DEFAULT_DATE_FORMAT).format(dateTemplate);
}
/**
 * 时间(dateTime)的 render
 * @export
 * @param {?String} dateTimeStr - 时间日期的字符串
 * @returns
 */

export function dateTimeRender(dateTimeStr) {
  var dateTimeTemplate = getDateTimeFormat();
  return dateTimeStr && moment(dateTimeStr, DEFAULT_DATETIME_FORMAT).format(dateTimeTemplate);
}
/**
 * 时间(time)的 render
 * @param {?String} timeStr - 时间日期的字符串
 */

export function timeRender(timeStr) {
  var timeTemplate = getTimeFormat();
  return timeStr && moment(timeStr, DEFAULT_DATETIME_FORMAT).format(timeTemplate);
}
/* 时区 对应的 moment.utcOffset */

export var timeZone2MomentUTC = {
  'GMT-12': -12,
  'GMT-11': -11,
  'GMT-10': -10,
  'GMT-9': -9,
  'GMT-8': -8,
  'GMT-7': -7,
  'GMT-6': -6,
  'GMT-5': -5,
  'GMT-4': -4,
  'GMT-3': -3,
  'GMT-2': -2,
  'GMT-1': -1,
  GMT: 0,
  'GMT+1': 1,
  'GMT+2': 2,
  'GMT+3': 3,
  'GMT+4': 4,
  'GMT+5': 5,
  'GMT+6': 6,
  'GMT+7': 7,
  'GMT+8': 8,
  'GMT+9': 9,
  'GMT+10': 10,
  'GMT+11': 11,
  'GMT+12': 12
};
/**
 * 依据时区格式化时间
 * @param {moment|string} time
 * @returns {?string}
 */

export function timeRenderWithUTC(time) {
  if (!_isNil(time)) {
    var momentDate = moment(time, DEFAULT_TIME_FORMAT);

    if (momentDate.isValid()) {
      var timeZone = getTimeZone();
      var utc = timeZone2MomentUTC[timeZone] || 8;
      var utcMoment = momentDate.utcOffset(utc);

      if (utcMoment.isValid()) {
        var timeFormat = getTimeFormat();
        return utcMoment.format(timeFormat);
      }
    }
  }
}
/**
 * 执行器-注册方式
 * @param {0|1|any} addressType
 * @return 0 -> 自动注册(多语言), 1 -> 手动录入(多语言), other -> ''
 */

export function addressTypeRender(addressType) {
  // eslint-disable-next-line no-nested-ternary
  return addressType === 0 ? intl.get('cpaas.common.jobGroup.auto').d('自动注册') : addressType === 1 ? intl.get('cpaas.common.jobGroup.byHand').d('手动录入') : '';
}
/**
 * 是否出错 - 渲染方式
 * @param {1|any} v
 * @return 1 -> yes(多语言), other -> no(多语言)
 */

export function isErrorOrNoRender(v) {
  var statusErrorOrNo = ['success', 'error'];
  return /*#__PURE__*/React.createElement(Badge, {
    status: statusErrorOrNo[v],
    text: v === 1 ? intl.get('cpaas.common.status.yes').d('是') : intl.get('cpaas.common.status.no').d('否')
  });
}
/**
 * 渲染审批动作描述
 * @param {string} action - 审批代码
 */

export function approveNameRender(action) {
  var actionText = action;

  switch (action) {
    case 'Approved':
      actionText = /*#__PURE__*/React.createElement(Tag, {
        color: "green"
      }, intl.get('cpaas.common.status.agree').d('同意'));
      break;

    case 'Rejected':
      actionText = /*#__PURE__*/React.createElement(Tag, {
        color: "red"
      }, intl.get('cpaas.common.status.reject').d('拒绝'));
      break;

    case 'AddSign':
      actionText = /*#__PURE__*/React.createElement(Tag, {
        color: "gold"
      }, intl.get('cpaas.common.status.addSign').d('加签'));
      break;

    case 'ApproveAndAddSign':
      actionText = /*#__PURE__*/React.createElement(Tag, {
        color: "gold"
      }, intl.get('cpaas.common.status.ApproveAndAddSign').d('同意并加签'));
      break;

    case 'Delegate':
      actionText = /*#__PURE__*/React.createElement(Tag, {
        color: "gold"
      }, intl.get('cpaas.common.status.delegate').d('转交'));
      break;

    case 'Jump':
      actionText = /*#__PURE__*/React.createElement(Tag, {
        color: "gold"
      }, intl.get('cpaas.common.status.jump').d('驳回'));
      break;

    case 'Recall':
      actionText = /*#__PURE__*/React.createElement(Tag, {
        color: "gold"
      }, intl.get('cpaas.common.status.recall').d('撤回'));
      break;

    case 'Revoke':
      actionText = /*#__PURE__*/React.createElement(Tag, {
        color: "orange"
      }, intl.get('cpaas.common.status.revoke').d('撤销'));
      break;

    case 'AutoDelegate':
      actionText = /*#__PURE__*/React.createElement(Tag, {
        color: "gold"
      }, intl.get('cpaas.common.status.autoDelegate').d('自动转交'));
      break;

    case 'CarbonCopy':
      actionText = /*#__PURE__*/React.createElement(Tag, {
        color: "gold"
      }, intl.get('cpaas.common.status.carbonCopy').d('抄送'));
      break;

    default:
      break;
  }

  return actionText;
}
/**
 * 格式化数值
 * 当 value 为 undefined,null,'',NaN,Infinity,-Infinity时 返回 ''
 * @param {string|number} value 需要格式化的数
 * @param {number} [precision=0] 数值精度 必须为自然数(0+正整数)
 * @param {boolean} [allowThousandth=true] 是否加上千分位
 * @param {boolean} [allowEndZero=true] 是否补全末尾0
 * @return {string}
 */

export function numberRender(value) {
  var precision = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  var allowThousandth = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
  var allowEndZero = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;

  if ( // 空检查
  value === null || value === undefined || value === '' || // 非法数值的检查
  +value === Infinity || +value === -Infinity || isNaN(+value)) {
    return '';
  } // 将 value 转为字符串并移除千分位


  var valueObject = new Big(String(value).replace(/,/g, ''));
  var ret = valueObject.toFixed(precision);

  if (allowThousandth) {
    var retList = ret.split('.');
    var commaValue = retList[0].replace(/\B(?=(\d{3})+(?!\d))/g, ','); // 整数部分千分位替换

    if (retList.length > 1) {
      ret = [commaValue, retList[1]].join('.');
    } else {
      ret = commaValue;
    }
  }

  if (!allowEndZero && ret.indexOf('.')) {
    return ret.replace(/(0|\.0)*$/, '');
  }

  return ret;
}
/**
 * 返回 激活/未激活 对应的多语言 并加上状态
 * @param {0|1} v 激活状态
 * return 1 ? enable(多语言) : disabled(多语言)
 */

export function activateRender(v) {
  return /*#__PURE__*/React.createElement(Badge, {
    status: statusMap[v],
    text: v === 1 ? intl.get('cpaas.common.active').d('激活') : intl.get('cpaas.common.notActive').d('未激活')
  });
}
/**
 * 返回状态标记
 * @param {string} status - 当前状态值
 * @param {array} statusList - 状态列表：[{ color: '' , status: '' }]
 * @param {string} text - 当前状态文本值
 */

export function TagRender(status) {
  var statusList = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
  var text = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';
  if (status === '' || status === undefined || status === null) return '';
  var currentStatus = statusList.find(function (item) {
    return item.status === status;
  }) || statusList.find(function (item) {
    return item.status === 'default';
  }) || {};
  return /*#__PURE__*/React.createElement(Tag, {
    color: currentStatus.color || ''
  }, text || currentStatus.text);
}
/**
 * @typedef {Object} OperatorAction
 * @property {string} key           - as key of operator
 * @property {React.CElement} ele   - React.Element
 */

/**
 * @typedef CloneAction
 * @param {OperatorAction} action
 * @param {any} record
 * @param {Object} options - 配置
 * @param {'button'|'menu'} options.type - 该操作在 外面 还是 在 Dropdown 中
 * @return React.ReactElement
 */

function defaultCloneAction(action, record) {
  var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  var _action$len = action.len,
      len = _action$len === void 0 ? 2 : _action$len,
      _action$title = action.title,
      title = _action$title === void 0 ? null : _action$title,
      key = action.key,
      ele = action.ele,
      noTooltip = action.noTooltip,
      _action$placement = action.placement,
      placement = _action$placement === void 0 ? 'top' : _action$placement;
  var type = options.type;
  var itemProps = {
    key: key
  };

  if (type === 'button') {
    var actionClassName = "action-link-item-".concat(len > 10 ? 10 : len);
    itemProps.className = ele.props && ele.props.className ? "".concat(ele.props.className, " ").concat(actionClassName) : actionClassName;
  }

  var item = React.cloneElement(ele, itemProps);

  if (title === null || type === 'menu' || noTooltip) {
    return item;
  }

  return React.createElement(Tooltip, {
    title: title,
    key: key,
    placement: placement
  }, item);
}
/**
 * 渲染表格操作列
 * @param {OperatorAction[]} actions
 * @param {any} record
 * @param {Object} options
 * @param {CloneAction} options.cloneAction
 * @param {number} [options.limit=3] - 控制操作外面显示多少操作
 */


export function operatorRender() {
  var actions = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
  var record = arguments.length > 1 ? arguments[1] : undefined;
  var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  var _options$cloneAction = options.cloneAction,
      cloneAction = _options$cloneAction === void 0 ? defaultCloneAction : _options$cloneAction,
      _options$limit = options.limit,
      limit = _options$limit === void 0 ? 3 : _options$limit,
      _options$label = options.label,
      label = _options$label === void 0 ? intl.get('cpaas.common.button.action').d('操作') : _options$label;
  var newActions = actions.filter(function (action) {
    return (// 过滤掉 没有的 action 与, ele 为 非 react 显示值 的元素
      action && !(action.ele === undefined || action.ele === null || action.ele === false || action.ele === true)
    );
  });

  if (newActions.length <= limit) {
    return /*#__PURE__*/React.createElement("span", {
      className: "action-link"
    }, newActions.map(function (action) {
      return cloneAction(action, record, {
        type: 'button'
      });
    }));
  }

  var sliceIndex = limit > 0 ? limit - 1 : 0;
  var opts = newActions.slice(0, sliceIndex);
  var moreOpts = newActions.slice(sliceIndex);
  var menu = /*#__PURE__*/React.createElement(Menu, null, moreOpts.map(function (action) {
    var key = action.key;
    return /*#__PURE__*/React.createElement(Menu.Item, {
      key: key
    }, cloneAction(action, record, {
      type: 'menu'
    }));
  }));
  return /*#__PURE__*/React.createElement("span", {
    className: "action-link"
  }, opts.map(function (action) {
    return cloneAction(action, record, {
      type: 'button'
    });
  }), /*#__PURE__*/React.createElement(Dropdown, {
    overlay: menu
  }, /*#__PURE__*/React.createElement("a", {
    className: "action-link-operation"
  }, label, /*#__PURE__*/React.createElement(Icon, {
    type: "down"
  }))));
}